package com.lxlx.weixinlx.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author liuhuan
 * @date
 * @描述 导出.csv文件
 */
public class CsvExportUtils {
    /** CSV文件列分隔符 */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /** CSV文件列分隔符 */
    private static final String CSV_RN = "\r\n";

    /**
     *
     * @param dataList 集合数据
     * @param colNames 表头部数据
     * @param mapKey 查找的对应数据
     * @param os 返回结果
     */
    public static void doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) throws IOException {

            StringBuffer buf = new StringBuffer();
            String[] colNamesArr = null;
            String[] mapKeyArr = null;
            colNamesArr = colNames.split(",");
            mapKeyArr = mapKey.split(",");
            // 完成数据csv文件的封装
            // 输出列头
            for (String aColNamesArr : colNamesArr) {
                buf.append(aColNamesArr).append(CSV_COLUMN_SEPARATOR);
            }
            buf.append(CSV_RN);
            // 输出数据
            if (null != dataList) {
                for (Map<String, Object> aDataList : dataList) {
                    for (String aMapKeyArr : mapKeyArr) {
                        buf.append("\t" +aDataList.get(aMapKeyArr) +"\t").append(CSV_COLUMN_SEPARATOR);
                    }
                    buf.append(CSV_RN);
                }
            }
            // 写出响应
            os.write(buf.toString().getBytes("GBK"));
            os.flush();


    }

    /**
     * setHeader
     */
    public static void responseSetProperties(String fileName, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        response.setContentType("text/csv");
        String codedFileName = URLEncoder.encode(fileName, "UTF-8");
        if (agent.contains("firefox")) {
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".csv" );
        } else {
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".csv");
        }

    }

}
